package com.book.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class login extends HttpServlet {

    private static final long serialVersionUID = 1L;
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://127.0.0.1:3306/library?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true";
    static final String USER = "root";
    static final String PASS = "1234";
    public void init() {

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        String iduser = req.getParameter("id");
        String passuser = req.getParameter("pass");
        HttpSession session = req.getSession();
        session.setAttribute("iduser", iduser);
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASS);
            stmt = conn.createStatement();
            String sql = String.format("SELECT passnum,manager FROM `user`WHERE id ='%s'" , iduser);
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                String passnum = rs.getString("passnum");
                String sr = rs.getString("manager");
                if (passuser.equals(passnum)) {
                    if ("yes".equals(sr))
                        req.getRequestDispatcher("/personmanager.jsp").forward(req, resp);
                    else{
                        req.getRequestDispatcher("/1.jsp").forward(req, resp);
                    }
                }
                else
                    req.getRequestDispatcher("/worry.html").forward(req, resp);
            }
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}
